package com.eternal.framework.component;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;

import com.eternal.framework.utils.Utils;

/**
 *
 * @author li
 */

public class BaseApplication extends Application {
    private static Application sInstance;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * 当主工程没有继承BaseApplication时，可以使用setApplication方法初始化BaseApplication
     *
     * @param application app
     */
    public static synchronized void setApplication(@NonNull Application application, final AppStateChangeListener appStateChangeListener) {
        sInstance = application;
        //初始化工具类
        Utils.init(application);
        //注册监听每个activity的生命周期,便于堆栈式管理
        application.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            private int resumeActivityCount = 0;

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                AppManager.getAppManager().addActivity(activity);
            }

            @Override
            public void onActivityStarted(Activity activity) {
                AppManager.getAppManager().addStart();
                if (resumeActivityCount++ == 0 && appStateChangeListener != null) {
                    // 执行切换到前台的逻辑
                    appStateChangeListener.appTurnIntoForeground();
                }
            }

            @Override
            public void onActivityResumed(Activity activity) {
            }

            @Override
            public void onActivityPaused(Activity activity) {
            }

            @Override
            public void onActivityStopped(Activity activity) {
                AppManager.getAppManager().subStart();
                if (--resumeActivityCount == 0 && appStateChangeListener != null) {
                    // 执行切换到后台的逻辑
                    appStateChangeListener.appTurnIntoBackGround();
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                AppManager.getAppManager().removeActivity(activity);
            }
        });
    }

    /**
     * 获得当前app运行的Application
     */
    public static Application getInstance() {
        if (sInstance == null) {
            throw new NullPointerException("please inherit BaseApplication or call setApplication.");
        }
        return sInstance;
    }

    public interface AppStateChangeListener {
        void appTurnIntoForeground();
        void appTurnIntoBackGround();
    }

}
